package com.chuanyang.driverh.mainhome;


import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainorder.GoodOwnerInfoActivity;
import com.chuanyang.driverh.mainorder.adapter.OrderInfoAdapter;
import com.chuanyang.driverh.mainother.BeforeNaviActivity;
import com.chuanyang.driverh.response2.ResultOrderOprate;
import com.chuanyang.driverh.response2.ResultWaitTransDriver;
import com.chuanyang.driverh.responseresult.OrderAddressResult;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.responseresult.OrderDetailData;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.responseresult.ValidateCodeResult;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.TimeUtils;
import com.chuanyang.driverh.utils.eventbus.CloseActivityEvent;
import com.chuanyang.driverh.utils.eventbus.EventBusUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.chuanyang.driverh.utils.widget.CustomMeasureHeightListView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;


public class OrderDetailRceiveActivity extends BaseTitleActivity {
    private ImageView iv_oredrinfo_peopleicon;//头像
    private ImageView iv_level;//级别
    private ImageView iv_dial;//级别
    private TextView tv_oredrinfo_peoplename;
    private TextView tv_oredrinfo_dingyue;
    private TextView tv_oredrinfo_phone;
    private TextView tv_oredrinfo_orderdate;
    private RatingBar rb_orderinfo_stars;
    private TextView tv_addr_start;
    private TextView tv_name_start;
    private TextView tv_phone_start;
    private ImageView iv_phone_start;
    private TextView tv_addr_end;
    private TextView tv_name_end;
    private TextView tv_phone_end;
    private ImageView iv_phone_end;
    private LinearLayout ll_orderinfo_cartimediv;
    private TextView tv_oredrinfo_deliverydate;
    private TextView tv_oredrinfo_picuupdate;
    private LinearLayout ll_orderinfo_shiptimediv;
    private TextView tv_shouzai;
    private TextView tv_load_day;
    private TextView tv_expect_arrive_date;
    private TextView tv_currency;

    private TextView tv_oredrinfodetail_demurrage;
    private TextView tv_oredrinfodetail_orderid;
    private TextView tv_oredrinfodetail_taskname;
    private TextView tv_oredr_num;
    private TextView tv_oredr_weight;
    private TextView tv_oredr_money;

    private TextView tv_act_num;
    private TextView tv_act_weight;
    private TextView tv_act_money;

    private LinearLayout ll_act_num;
    private LinearLayout ll_act_weight;
    private LinearLayout ll_act_money;


    private TextView tv_oredrinfo_remark;
    private TextView tv_left;
    private TextView tv_right;
    private LinearLayout ll_buttons;
    private CustomMeasureHeightListView lv_orderlist;
    private Dialog dialog;

    private OrderDetailData data;
    private String orderId;
    private String bidId;
    private String type = "0";//0,进入后只显示详情，没有按钮,1,竞价列表进入，显示竞价按钮，可竞价

    private AlertDialog alertDialog;
    private EditText et_sureunload_code;
    private TextView tv_cancle_unload;
    private TextView tv_sureunload_getcode;
    private TextView tv_sure_unload;
    //为了竞价单加的
    private LinearLayout ll_weight_num;
    private LinearLayout ll_my_bid_price;
    private TextView tv_my_bid_price;


    private String minPrice = "";

    private boolean validateOk;
    private String phoneNum;
    private String fleetOrPerson = "2";//接单列表进入，是个人单还是车队单，2，车队，1个人。

    private ArrayList<File> files;

    private LinearLayout ll_oredrinfo_goodownerdiv;
  /*  private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:  //1是车队
                    receiveOrder("2");
                    break;
                case 2:  //1是个人
                    receiveOrder("1");
                    break;


                case 3://确认收货运单，1，订单
                    validateCode((String) msg.obj, 1);
                    break;

            }
        }
    };
*/
    @Override
    protected int getContentResId() {
        return R.layout.home_act_orderdetail_receive;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        showActivityLoading();
        iv_oredrinfo_peopleicon = (ImageView) findViewById(R.id.iv_oredrinfo_peopleicon);
        iv_level = (ImageView) findViewById(R.id.iv_level);
        iv_dial = (ImageView) findViewById(R.id.iv_dial);
        tv_oredrinfo_peoplename = (TextView) findViewById(R.id.tv_oredrinfo_peoplename);
        tv_oredrinfo_dingyue = (TextView) findViewById(R.id.tv_oredrinfo_dingyue);
        tv_oredrinfo_phone = (TextView) findViewById(R.id.tv_oredrinfo_phone);
        tv_oredrinfo_orderdate = (TextView) findViewById(R.id.tv_oredrinfo_orderdate);
        rb_orderinfo_stars = (RatingBar) findViewById(R.id.rb_orderinfo_stars);

        tv_addr_start = (TextView) findViewById(R.id.tv_addr_start);
        tv_name_start = (TextView) findViewById(R.id.tv_name_start);
        tv_phone_start = (TextView) findViewById(R.id.tv_phone_start);
        iv_phone_start = (ImageView) findViewById(R.id.iv_phone_start);

        tv_addr_end = (TextView) findViewById(R.id.tv_addr_end);
        tv_name_end = (TextView) findViewById(R.id.tv_name_end);
        tv_phone_end = (TextView) findViewById(R.id.tv_phone_end);
        iv_phone_end = (ImageView) findViewById(R.id.iv_phone_end);

        ll_orderinfo_cartimediv = (LinearLayout) findViewById(R.id.ll_orderinfo_cartimediv);
        tv_oredrinfo_deliverydate = (TextView) findViewById(R.id.tv_oredrinfo_deliverydate);
        tv_oredrinfo_picuupdate = (TextView) findViewById(R.id.tv_oredrinfo_picuupdate);

        ll_orderinfo_shiptimediv = (LinearLayout) findViewById(R.id.ll_orderinfo_shiptimediv);
        tv_shouzai = (TextView) findViewById(R.id.tv_shouzai);
        tv_load_day = (TextView) findViewById(R.id.tv_load_day);
        tv_expect_arrive_date = (TextView) findViewById(R.id.tv_expect_arrive_date);
        tv_currency = (TextView) findViewById(R.id.tv_currency);
        tv_oredrinfodetail_demurrage = (TextView) findViewById(R.id.tv_oredrinfodetail_demurrage);

        tv_oredrinfodetail_orderid = (TextView) findViewById(R.id.tv_oredrinfodetail_orderid);
        tv_oredrinfodetail_taskname = (TextView) findViewById(R.id.tv_oredrinfodetail_taskname);
        tv_oredr_num = (TextView) findViewById(R.id.tv_oredr_num);
        tv_oredr_weight = (TextView) findViewById(R.id.tv_oredr_weight);
        tv_oredr_money = (TextView) findViewById(R.id.tv_oredr_money);

        tv_act_num = (TextView) findViewById(R.id.tv_act_num);
        tv_act_weight = (TextView) findViewById(R.id.tv_act_weight);
        tv_act_money = (TextView) findViewById(R.id.tv_act_money);

        ll_act_num = (LinearLayout) findViewById(R.id.ll_act_num);
        ll_act_weight = (LinearLayout) findViewById(R.id.ll_act_weight);
        ll_act_money = (LinearLayout) findViewById(R.id.ll_act_money);
        tv_oredrinfo_remark = (TextView) findViewById(R.id.tv_oredrinfo_remark);
        lv_orderlist = (CustomMeasureHeightListView) findViewById(R.id.lv_orderlist);
        tv_left = (TextView) findViewById(R.id.tv_left);
        tv_right = (TextView) findViewById(R.id.tv_right);
        ll_buttons = (LinearLayout) findViewById(R.id.ll_buttons);


        tv_my_bid_price = (TextView) findViewById(R.id.tv_my_bid_price);
        ll_weight_num = (LinearLayout) findViewById(R.id.ll_weight_num);
        ll_my_bid_price = (LinearLayout) findViewById(R.id.ll_my_bid_price);
        ll_oredrinfo_goodownerdiv = (LinearLayout) findViewById(R.id.ll_oredrinfo_goodownerdiv);

    }

    @Override
    protected void initData() {
        setBackImg();
        getRightTextView().setText("状态");
        getTitleTextView().setText("订单详情");
        orderId = getIntent().getStringExtra("data");
        bidId = getIntent().getStringExtra("bidId");
        type = getIntent().getStringExtra("type");

        if (getIntent().getStringExtra("fleetOrPerson") != null) {
            fleetOrPerson = getIntent().getStringExtra("fleetOrPerson");
        }

        if ("1".equals(type)) {
            if (StringUtil.isBlank(getIntent().getStringExtra("minPrice"))) {
                minPrice = "";
            } else {
                minPrice = getIntent().getStringExtra("minPrice");
            }
        } else if ("2".equals(type)) {
            if (StringUtil.isBlank(getIntent().getStringExtra("minPrice"))) {
                minPrice = "";
            } else {
                minPrice = getIntent().getStringExtra("minPrice");
            }
        }

        ///0,进入后只显示详情，没有按钮,1,竞价列表进入，显示竞价按钮，可竞价。2接单列表进入，需要显示重新竞价。
        /// 3、ReceiveOrderActivity进入，跳出的接单界面进入。//4接单列表，待处理进入显示两个按钮
        //5、车辆安排进入，只有派单按钮，6，有查看运单、派单两个按钮，7，只有查看运单按钮。
        //8、车队长代运实发进入，有查看运单，完成订单两个按钮，9，只有完成订单一个按钮。10,个人单接的单，根据情况显示1个或两个按钮。
        //11收款跟踪进入，有查看运单按钮，

        if ("0".equals(type)) {
            ll_buttons.setVisibility(View.GONE);
        } else if ("1".equals(type)) {
            ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.GONE);
            tv_right.setVisibility(View.VISIBLE);
            tv_right.setText("竞价");
            getRightTextView().setVisibility(View.GONE);

            ll_weight_num.setVisibility(View.GONE);
            ll_my_bid_price.setVisibility(View.VISIBLE);
            tv_my_bid_price.setText("最低竞价：  " + minPrice);


        } else if ("2".equals(type)) {
            ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.VISIBLE);
            tv_left.setText("放弃");
            tv_right.setVisibility(View.VISIBLE);
            tv_right.setText("重新竞价");

            ll_weight_num.setVisibility(View.GONE);
            ll_my_bid_price.setVisibility(View.VISIBLE);
            tv_my_bid_price.setText("我的竞价：  " + minPrice);

        } else if ("3".equals(type)) {
            ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.VISIBLE);
            tv_right.setVisibility(View.VISIBLE);
            tv_left.setText("放弃");
            tv_right.setText("接单");
        } else if ("4".equals(type)) {
            ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.VISIBLE);
            tv_right.setVisibility(View.VISIBLE);
            tv_left.setText("放弃");
            tv_right.setText("接单");
        } else if ("5".equals(type)) {
            ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.GONE);
            tv_right.setVisibility(View.VISIBLE);
            tv_right.setText("派单");
        } else if ("6".equals(type)) {
            ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.VISIBLE);
            tv_right.setVisibility(View.VISIBLE);
            tv_left.setText("查看派单");
            tv_right.setText("派单");
        } else if ("7".equals(type)) {
            ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.GONE);
            tv_right.setVisibility(View.VISIBLE);
            tv_right.setText("查看派单");
        } else if ("8".equals(type)) {
            ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.VISIBLE);
            tv_right.setVisibility(View.VISIBLE);
            tv_left.setText("完成订单");
            tv_right.setText("查看运单");
        } else if ("9".equals(type)) {
            ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.GONE);
            tv_right.setVisibility(View.VISIBLE);
            tv_right.setText("查看运单");
        } else if ("10".equals(type)) {
            //根据订单状态显示开始运输等按钮,先隐藏，加载数据之后再显示按钮。
            ll_buttons.setVisibility(View.GONE);
        } else if ("11".equals(type)) {
            ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.GONE);
            tv_right.setVisibility(View.VISIBLE);
            tv_right.setText("查看运单");
        }
        requsetData(orderId);
    }

    @Override
    protected void initListener() {
        iv_dial.setOnClickListener(this);
        tv_left.setOnClickListener(this);
        tv_right.setOnClickListener(this);
        ll_oredrinfo_goodownerdiv.setOnClickListener(this);

    }

    private void updateUi(OrderDetailData orderDetail) {
        if (orderDetail != null) {
            String moneyUnit = "¥";
            if (orderDetail.getCurrency() == 1) {
                moneyUnit = "¥";
            } else {
                moneyUnit = "$";
            }
            if ("1".equals(type)) {
                if (!StringUtil.isBlank(minPrice)) {
                    minPrice = minPrice + moneyUnit + "/t";
                    tv_my_bid_price.setText("最低竞价：   " + minPrice);
                }

            } else if ("2".equals(type)) {
                if (!StringUtil.isBlank(minPrice)) {
                    minPrice = minPrice + moneyUnit + "/t";
                    tv_my_bid_price.setText("我的竞价：   " + minPrice);
                }
            }


            BitmapUtil.showImgForNetPath(data.getUserImage(), iv_oredrinfo_peopleicon);
            //// TODO: 2017/4/11
//            iv_level
            tv_oredrinfo_peoplename.setText(data.getUsername());
            if (data.getSubscriptionStatus() == 1) {
                tv_oredrinfo_dingyue.setText("已订阅");
            } else if (data.getSubscriptionStatus() == 2) {
                tv_oredrinfo_dingyue.setText("未订阅");
            }
            tv_oredrinfo_phone.setText(StringUtil.handlePhoneNumShow(data.getPhone()));
            tv_oredrinfo_orderdate.setText(TimeUtils.getStandardTime(data.getOrder_time()));
            rb_orderinfo_stars.setRating(data.getStar());
            for (OrderDetailData.PassPointsBean bean : data.getPassPoints()) {
                if ("s".equals(bean.getPointType())) {
                    tv_addr_start.setText(bean.getProvince() + bean.getCity() + bean.getRegions() + "\n" + bean.getAddress());
                    tv_name_start.setText(bean.getContactPerson());
                    final String phoneStart = bean.getContactPhone();
                    tv_phone_start.setText(StringUtil.handlePhoneNumShow(phoneStart));
                    iv_phone_start.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DialogUtil.dial(activityContext, phoneStart);

                        }
                    });
                } else if ("e".equals(bean.getPointType())) {
//                    tv_addr_end.setText(bean.getCity() + " " + bean.getDetailAdress());
                    tv_addr_end.setText(bean.getProvince() + bean.getCity() + bean.getRegions() + "\n" + bean.getAddress());

                    tv_name_end.setText(bean.getContactPerson());
                    final String phoneEnd = bean.getContactPhone();
                    tv_phone_end.setText(StringUtil.handlePhoneNumShow(phoneEnd));
                    iv_phone_end.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            dial(phoneEnd);
                            DialogUtil.dial(activityContext, phoneEnd);
                        }
                    });
                }
            }
            if (data.getTransPortWay() == 1)//车
            {
                tv_oredrinfo_deliverydate.setText(TimeUtils.getStandardTime(data.getOrder_startime()));
                if (data.getOrder_endtime() == 0) {
                    tv_oredrinfo_picuupdate.setText("不限");
                } else {
                    tv_oredrinfo_picuupdate.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));
                }
                ll_orderinfo_cartimediv.setVisibility(View.VISIBLE);
                ll_orderinfo_shiptimediv.setVisibility(View.GONE);

            } else if (data.getTransPortWay() == 2)//船
            {
                /*tv_driverinfo_loaddatebeg.setText(data.getLoadDate());
                tv_driverinfo_loaddateend.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));
                tv_driverinfo_stevedoreDaybeg.setText(data.getStevedoreDay());
                tv_driverinfo_stevedoreDayend.setText(data.getFq());*/

                tv_load_day.setText(data.getStevedoreDay());
                tv_shouzai.setText(TimeUtils.getStandardTimeDay(data.getOrder_startime()) + "±" + data.getFq() + "天");
                tv_expect_arrive_date.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));

                tv_oredrinfodetail_demurrage.setText(data.getDemurrage() + moneyUnit + "/天/吨");
                ll_orderinfo_cartimediv.setVisibility(View.GONE);
                ll_orderinfo_shiptimediv.setVisibility(View.VISIBLE);

            }

            tv_oredrinfodetail_orderid.setText(data.getOrderNo());
            if (!TextUtils.isEmpty(data.getAssignment())) {
                tv_oredrinfodetail_taskname.setText(data.getAssignment());
            } else {
                tv_oredrinfodetail_taskname.setVisibility(View.GONE);
            }

            if (orderDetail.getGoodsSum() != null) {
                tv_oredr_weight.setText(orderDetail.getGoodsSumWeight() + "t");
                tv_oredr_num.setText("" + orderDetail.getGoodsSumNum());
                double orginamount = (orderDetail.getGoodsSum().getGoodsWeight()) * (orderDetail.getPrice());
                if (data.getOrder_type() == 1 && data.getOrder_status() == 0) {
                    tv_oredr_money.setText("***");
                } else {
                    tv_oredr_money.setText(StringUtil.getDouble(orginamount + "") + moneyUnit);
                }
            }
            if (data.getRealitySum() != null) {
                tv_act_num.setText(data.getRealitySum().getRealityNum() + "");
                tv_act_weight.setText(StringUtil.getDouble(data.getRealitySum().getRealityWeight() + "") + "t");

                double actMount = (orderDetail.getRealitySum().getRealityWeight()) * (orderDetail.getPrice());
                tv_act_money.setText(StringUtil.getDouble(actMount + "") + moneyUnit);

                ll_act_num.setVisibility(View.VISIBLE);
                ll_act_weight.setVisibility(View.VISIBLE);
                ll_act_money.setVisibility(View.VISIBLE);
            } else {
                ll_act_num.setVisibility(View.GONE);
                ll_act_weight.setVisibility(View.GONE);
                ll_act_money.setVisibility(View.GONE);
            }
//            tv_act_num = (TextView) findViewById(R.id.tv_act_num);
//            tv_act_weight = (TextView) findViewById(R.id.tv_act_weight);
//            tv_act_money = (TextView) findViewById(R.id.tv_act_money);


            tv_oredrinfo_remark.setText(data.getRemark());
            OrderInfoAdapter orderInfoAdapter = new OrderInfoAdapter(this, data.getDetailList());
            lv_orderlist.setAdapter(orderInfoAdapter);
            if (data.getCurrency() == 2) {
                tv_currency.setText("外贸");
            } else {
                tv_currency.setText("内贸");
            }

        }
        hideActivityLoading();
    }

    private void requsetData(String orderId) {
        DialogUtil.showLoadingDialog(activityContext, "请求中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", orderId);
        MyHttpUtil.selectOrderMsgById(activityContext, params, new MyCallback<OrderDatailResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    data = result.getData();
                    updateUi(data);
                    hideActivityLoading();

                    if (data != null && data.getOrder_status() != 0) {
                        orderStatus = data.getOrder_status();
                        ifShowButtons(data.getOrder_status());
                    }
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });

    }

    private int orderStatus;

    private void ifShowButtons(int status) {
        if ("10".equals(type)) {
           /* ll_buttons.setVisibility(View.VISIBLE);
            tv_left.setVisibility(View.VISIBLE);
            tv_right.setVisibility(View.VISIBLE);
            if (status <= 3 && status > 0) {
                tv_left.setVisibility(View.GONE);
                tv_right.setText("开始运输");
            } else if (status == 4) {
                tv_left.setText("导航");
                tv_right.setText("运输完成");
            } else if (status == 5) {
                tv_left.setText("导航");
                tv_right.setText("运输完成");
            } else if (status == 6) {
                tv_left.setVisibility(View.GONE);
                tv_right.setText("验证卸货");
            }else {
                ll_buttons.setVisibility(View.GONE);
            }*/


         ll_buttons.setVisibility(View.VISIBLE);
        tv_left.setVisibility(View.GONE);
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("查看运单");

        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_dial:
                DialogUtil.dial(activityContext, data.getPhone());
                break;
            case R.id.tv_left:
                leftClick();
                break;
            case R.id.tv_right:
                rightClick();
                break;
            case R.id.ll_oredrinfo_goodownerdiv:
                if (data != null) {
                    startActivity(GoodOwnerInfoActivity.class, data);
                }
                break;
        }
    }

    ///0,进入后只显示详情，没有按钮,1,竞价列表进入，显示竞价按钮，可竞价。2竞价列表进入，需要显示重新竞价。
    /// 3、ReceiveOrderActivity进入，跳出的接单界面进入。//4接单列表，待处理进入显示两个按钮
    //5、车辆安排进入，只有派单按钮，6，有查看运单、派单两个按钮，7，只有查看运单按钮。
    //8、车队长代运实发进入，有查看运单，完成订单两个按钮，9，只有完成订单一个按钮。10,个人单接的单，根据情况显示1个或两个按钮。
    //11收款跟踪进入，有查看运单按钮，
    private void rightClick() {
        if ("1".equals(type)) {
            //竞价
            bidding();
        } else if ("3".equals(type)) {//接单
            receiveOrder("1");
        } else if ("2".equals(type)) {//接单列表进入
            if (data.getOrder_type() == 1) {//竞价
                requsetData();
            }
        } else if ("4".equals(type)) {//接单列表进入,待处理的匹配、专线单
            receiveOrder(fleetOrPerson);
           /* if (data!=null && data.getType()==2){
                receiveOrder("2");
            }else {
                receiveOrder("1");
            }*/
        } else if ("5".equals(type)) {
            startActivity(new Intent(activityContext, GoodsAssignWeightNumActivity.class).putExtra("data", orderId + ""));
        } else if ("6".equals(type)) {
            startActivity(new Intent(activityContext, GoodsAssignWeightNumActivity.class).putExtra("data", orderId + ""));
        } else if ("7".equals(type)) {
            startActivity(new Intent(activityContext, CarPlanWaybilListActivity.class).putExtra("data", orderId + ""));
        }/* else if ("8".equals(type)) {
            if (data != null && data.getStartAddr() != null) {
                Intent intent = new Intent(activityContext, WaybilListActivity.class);
                intent.putExtra("data", orderId + "");
                intent.putExtra("begin", data.getStartAddr());
                intent.putExtra("end", data.getTargetAddr());
                startActivity(intent);
            }
        } else if ("9".equals(type)) {
            if (data != null && data.getStartAddr() != null) {
                Intent intent = new Intent(activityContext, WaybilListActivity.class);
                intent.putExtra("data", orderId + "");
                intent.putExtra("begin", data.getStartAddr());
                intent.putExtra("end", data.getTargetAddr());
                startActivity(intent);
            }
        }*/ else if ("10".equals(type) ||"8".equals(type)||"9".equals(type) ) {

            Intent intent = new Intent(activityContext, WaybilListActivity.class);
            ResultWaitTransDriver.OutDataEntity.DataEntity waitTrasData= (ResultWaitTransDriver.OutDataEntity.DataEntity) getIntent().getSerializableExtra("waitTrasData");
            intent.putExtra("data", waitTrasData);
            startActivity(intent);
          /*  if (orderStatus <= 3) {
                //开始运输
                if (data != null && data.getWaybillSimpleMsg() != null && data.getWaybillSimpleMsg().getWaybillId() != 0)
                    startTranslate(data.getWaybillSimpleMsg().getWaybillId() + "");
            } else if (orderStatus == 4 || orderStatus == 5) {
                //确认卸货
                if (data != null && data.getOrderId() != 0) {
                    Intent intent = new Intent(activityContext, SureUnLoadOverActivity.class);
                    intent.putExtra("orederId", data.getOrderId());
                    intent.putExtra("fromlist", true);
                    intent.putExtra("personalOrder", true);
                    startActivity(intent);
                }
            } else if (orderStatus == 6) {
                if (data != null)
                    sureAcceptGood(data.getPhone(), orderId + "", 3);
            }*/
        }else if ("11".equals(type)) {
            if (data != null && data.getOrderId() != 0) {
                Intent intent = new Intent(activityContext, MoneyFollowWaybilListActivity.class);
                intent.putExtra("currency", data.getCurrency() + "");
                intent.putExtra("data", data.getOrderId() + "");
                startActivity(intent);
            }
        }
    }

    ///0,进入后只显示详情，没有按钮,1,竞价列表进入，显示竞价按钮，可竞价。2竞价列表进入，需要显示重新竞价。
    /// 3、ReceiveOrderActivity进入，跳出的接单界面进入。//4接单列表，待处理进入显示两个按钮
    //5、车辆安排进入，只有派单按钮，6，有查看运单、派单两个按钮，7，只有查看运单按钮。
    //8、车队长代运实发进入，有查看运单，完成订单两个按钮，9，只有查看运单一个按钮。10,个人单接的单，根据情况显示1个或两个按钮。
    private void leftClick() {
        if ("1".equals(type)) {

        } else if ("2".equals(type)) {

            cancelDialogShow();

        } else if ("3".equals(type)) {
            cancelDialogShow();
        } else if ("4".equals(type)) {
            cancelDialogShow();
        } else if ("5".equals(type)) {

        } else if ("6".equals(type)) {
            startActivity(new Intent(activityContext, CarPlanWaybilListActivity.class).putExtra("data", orderId + ""));
        } else if ("7".equals(type)) {

        } else if ("8".equals(type)) {
            if (data != null)
                completeDialogShow();
        } else if ("9".equals(type)) {

        } else if ("10".equals(type)) {
            //导航
            selectOrderAddress(orderId + "");

        }
    }

    private void completeDialogShow() {
        if (data.getOrder_status() < 4) {
            PrintUtil.toast(activityContext, "当前订单无法执行此操作");
            return;
        }
        dialog = DialogUtil.myDialog(activityContext, "完成订单", "取消", "确定", "确定完成订单？", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.dialog_btn_right) {
                    completeOrder(orderId);
                }
                dialog.cancel();
            }
        });
    }

    private void cancelDialogShow() {
        dialog = DialogUtil.myDialog(activityContext, "放弃", "取消", "确定", "确定放弃？", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.dialog_btn_left:
                        break;
                    case R.id.dialog_btn_right:
                        if ("2".equals(type)) {//放弃订单，竞价单放弃。
//                            orderSheve("2");
                            orderDelete(orderId,bidId);

                        }else  if ("3".equals(type)) {//放弃订单
                            orderSheve("2");
                        } else if ("4".equals(type)) {
                            orderSheve("2");
                        }
                        break;
                }
                dialog.cancel();
            }
        });
    }


    //竞价单放弃
    private void orderDelete(String orderId,String bidId) {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId",orderId+ "");
        params.put("bidId",bidId);
        params.put("type", "1");
        MyHttpUtil.deletePendOrder(activityContext, params, new MyCallback<OrderDatailResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    if (StringUtil.isBlank(result.getMsg())) {
                        PrintUtil.toast(activityContext, "操作成功");
                    } else {
                        PrintUtil.toast(activityContext, result.getMsg());
                    }
                    EventBus.getDefault().post(new RefleshFragEvent(0));
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }

            }
        });
    }



    private void bidding() {
        startActivity(BidOrderActivity.class, data);
    }

    private void requsetData() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", orderId + "");
        MyHttpUtil.selectOrderMsgById(activityContext, params, new MyCallback<OrderDatailResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(OrderDatailResult result, int id) {

                if (result.getCode() == ConstUtil.OK) {
                    Intent intent = new Intent(activityContext, BidOrderActivity.class);
                    intent.putExtra("data", result.getData());
                    intent.putExtra("bidId", bidId);
                    activityContext.startActivity(intent);
//                    activity.startActivity(new Intent(activity,BidOrderActivity.class).putExtra("data",result.getData()));

                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });

    }


    //订单搁置
    private void orderSheve(String oprateType) {//操作类型（1：接单，2：拒绝，3：搁置）
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", orderId);
        params.put("operate", oprateType);
        params.put("type", StringUtil.isBlank(SharedPrefUtil.getFleetId()) ? "1" : "2");//类型（1：个人，2：车队）
        MyHttpUtil.orderShelve(activityContext, params, new MyCallback<ResultOrderOprate>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(ResultOrderOprate result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    if (result.getMsg() != null) {
                        PrintUtil.toast(activityContext, result.getMsg());
                    } else {
                        PrintUtil.toast(activityContext, "操作成功");
                    }
                    finish();
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });


    }


    /**
     * 接单操作
     */
    private void receiveOrder(String type) {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderId", orderId);
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("type", type);
        if (data != null && !StringUtil.isBlank(data.getAppoint())) {
            params.put("appoint", data.getAppoint());
        } else {
            params.put("appoint", "1");
        }
        if (data != null) {
            params.put("orderType", data.getOrder_type() + "");
            params.put("amount", data.getOrder_Amount() + "");
        }
        MyHttpUtil.receiveOrder(activityContext, params, new MyCallback<Result>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    if (!StringUtil.isBlank(result.getMsg())) {
                        PrintUtil.toast(activityContext, result.getMsg());
                    } else {
                        PrintUtil.toast(activityContext, "操作成功");
                    }
                    EventBusUtil.postEvent(new CloseActivityEvent(1));
                    finish();
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });
    }


    private void completeOrder(String orderId) {
        DialogUtil.showLoadingDialog(activityContext, "请求中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("orderId", orderId + "");
        params.put("orderStatus", "6");
        MyHttpUtil.updateOrderStatusByWaybill(activityContext, params, new MyCallback<Result>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                e.printStackTrace();
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    EventBusUtil.postEvent(new RefleshFragEvent(3));
                    tv_left.setVisibility(View.GONE);
                } else {
                    if (result.getMsg() != null) {
                        PrintUtil.toast(activityContext, result.getMsg());
                    } else {
                        PrintUtil.toast(activityContext, "操作失败");
                    }
                }
            }
        });
    }

    /**
     * 导航请求数据
     *
     * @param id
     */
    private void selectOrderAddress(String id) {
        DialogUtil.showLoadingDialog(activityContext, "请求中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("orderId", id);
        MyHttpUtil.selectOrderAddress(activityContext, params, new MyCallback<OrderAddressResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                e.printStackTrace();
            }

            @Override
            public void onSuccess(OrderAddressResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    Intent intent = new Intent(activityContext, BeforeNaviActivity.class);
                    intent.putExtra("OrderAddressResult", result);
                    startActivity(intent);
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });
    }

    private void startTranslate(String waybillId) {
        DialogUtil.showLoadingDialog(activityContext, "请求中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("waybillId", waybillId + "");
        params.put("waybillStatus", "4");
        params.put("driverId", SharedPrefUtil.getUserId());
        MyHttpUtil.startTranslate(activityContext, params, new MyCallback<Result>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                e.printStackTrace();
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    orderStatus = 4;
                    ifShowButtons(4);
                    EventBusUtil.postEvent(new RefleshFragEvent(3));
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });


    }

    /**
     * 验证卸货
     *
     * @param phone id
     */
    public void sureAcceptGood(final String phone, final String id, final int type) {
        if (StringUtil.isBlank(phone)) {
            PrintUtil.toast(activityContext, "收货人电话为空");
            return;
        }
        if (null == alertDialog) {
            alertDialog = new AlertDialog.Builder(activityContext).create();
            alertDialog.show();
            alertDialog.setTitle(null);
            alertDialog.setCanceledOnTouchOutside(false);
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    alertDialog = null;
                }
            });
            Window window = alertDialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setBackgroundDrawable(new ColorDrawable(0));
            window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            window.setContentView(R.layout.dialog_sureunload);
            View view = window.getDecorView();
            et_sureunload_code = (EditText) view.findViewById(R.id.et_sureunload_code);
            tv_cancle_unload = (TextView) view.findViewById(R.id.tv_cancle_unload);
            tv_sureunload_getcode = (TextView) view.findViewById(R.id.tv_sureunload_getcode);
            tv_sure_unload = (TextView) view.findViewById(R.id.tv_sure_unload);
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    validateOk = false;

                }
            });
            tv_cancle_unload.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    alertDialog = null;
                }
            });
            tv_sureunload_getcode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!validateOk) {//获取成功验证码 且对话框没消失时无法多次点击
                        getValidateCode(phone, id);
                    } else {

                        PrintUtil.toast(activityContext, "验证码已发送给货主！");
                    }
                }
            });
            tv_sure_unload.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(et_sureunload_code.getText().toString().trim())) {
                        PrintUtil.toast(activityContext, "请填写获取到验证码");
                        return;
                    }
                    if (!validateOk){
                        PrintUtil.toast(activityContext,"请先获取验证码");
                        return;
                    }


                    updteOrderUnload(id);

//                    Message message = Message.obtain();
//                    message.obj = id;
//                    message.what = type;
//                    mHandler.sendMessage(message);
//                    alertDialog.dismiss();
//                    alertDialog = null;
                }
            });
        }
        //下面两行代码加入后即可弹出输入法
        alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    }


    /**
     * 获取验证码
     */
    private void getValidateCode(final String phone, String id) {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("phone", phone);
        params.put("validateMsg", id);
        MyHttpUtil.getSureValidateCode(activityContext, params, new MyCallback<ValidateCodeResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(ValidateCodeResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    phoneNum = phone;
                    validateOk = true;
                    tv_sureunload_getcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.tv_shape_gray_round_corner_solid));
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });


    }

  /*  private void validateCode(final String orderId, final int type) {
        if (StringUtil.isBlank(phoneNum)) return;
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("phone", phoneNum);
        params.put("validateCode", et_sureunload_code.getText().toString().trim());
        MyHttpUtil.validateCode(activityContext, params, new MyCallback<ValidateCodeIfTrueResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(ValidateCodeIfTrueResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    if (result.getData()) {
                        updateWaybillUnload(orderId, type);
                        alertDialog.dismiss();
                        alertDialog = null;
                    } else {
                        PrintUtil.toast(activityContext, "验证码有误");
                    }

                } else {
                    if (result.getMsg() != null) {
                        PrintUtil.toast(activityContext, result.getMsg());
                    } else {
                        PrintUtil.toast(activityContext, "验证失败");
                    }
                }
            }
        });


    }*/

    /**
     * 收货完成 （传入订单id或者运单id）
     */
   /* private void updateWaybillUnload(String id, int type) {//type0运单，1订单
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, Object> params = new HashMap<String, Object>();
        if (type == 0) {
            params.put("waybillId", id);
            params.put("waybillStatus", "7");
        } else {
            params.put("orderId", id);
            params.put("orderStatus", "7");
        }
        params.put("validateMsg", id + "");
        params.put("validateCode", et_sureunload_code.getText().toString().trim());
        MyHttpUtil.signoff(activityContext, params, new MyCallback<Result>(activityContext, new JsonGenericsSerializator()) {
            //        MyHttpUtil.updateOrderUnload(activity,null,params, new MyCallback<Result>(activity,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(activityContext, "您已替货主确认收货");
                    EventBusUtil.postEvent(new RefleshFragEvent(3));
                    orderStatus = 7;
                    ifShowButtons(7);
                } else {
//                    PrintUtil.toast(getActivity(),result.getMsg());
                }
            }
        });


    }*/
    /**
     * 代替货主收货接口 (个人订单时)
     */
    private void updteOrderUnload(String orderId) {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        if (files == null) {
            files = new ArrayList();
        }
        params.clear();
        params.put("orderId", orderId + "");
        params.put("orderStatus", "7");
        params.put("validateMsg", orderId + "");
        params.put("validateCode", et_sureunload_code.getText().toString().trim());
        MyHttpUtil.updateOrderUnload(activityContext,files,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(activityContext, "您已替货主确认收货");
                    EventBusUtil.postEvent(new RefleshFragEvent(3));
                    alertDialog.dismiss();
                    alertDialog = null;
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }
    @Override
    protected void baseGoEnsure() {
        super.baseGoEnsure();
        Intent intent = new Intent(activityContext, OrderStatusActivity.class);
        intent.putExtra("orderId", orderId + "");
        startActivity(intent);
    }


    public void onEventMainThread(RefleshFragEvent event) {
        if (event.getIndex() == 3) {
            if ("10".equals(type)) {
                orderStatus = 6;
                ifShowButtons(6);
            }
        }
    }
}
